import * as API_AfterSale from '../../../api/after-sale.js'
import {Foundation} from '../../../ui-utils/index.js'
import * as watch from "../../../utils/watch.js";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    order_sn:'',
    sku_id:'',
    order:'',//订单详情
    skuList:[],//货品列表
    type:'money',//申请售后类型
    //申请售后表单
    returnForm:{
      refund_reason: '',
      account_type: 'WEIXINPAY',
      order_sn:'',
      return_num: 1,
      return_money: 0,
      customer_remark: ''
    },
    maxReturnNum: 1,// 最大可退货数量
    isCancel: false,// 是否为取消订单模式
    applyReasons: ['商品质量有问题', '收到商品与描述不符', '不喜欢/不想要', '发票问题', '空包裹', '快递无记录', '快递一直没有收到',
      '买错/不想要', '未按照时间发货', '其他'],
    accountType:['支付宝','微信','银行转账'],
    reason_select:false,
    account_select:false,
    original_way:false,// 是否为原路退款
    //货物状态
    groups1: [
        { text: '未收到货', value: 1 },
        { text: '已收到货', value: 2 },
    ],
    showActionsheet1:false,
    //退货款理由
    groups2: [
        { text: '多拍/拍错/不想要', value: 1 },
        { text: '快递一直未送到', value: 2 },
        { text: '未按约定时间发货', value: 3 },
        { text: '快递无跟踪记录', value: 4 },
        { text: '其他', value: 5 },
    ],
    showActionsheet2:false,
    //换货理由
    groups3: [
      { text: '货物本身有质量问题', value: 1 },
      { text: '产品与描述不符', value: 2 },
      { text: '未按约定时间发货', value: 3 },
      { text: '发货检查不仔细', value: 4 },
      { text: '其他', value: 5 },
    ],
    showActionsheet3:false,
    state:'',
    reason:'',
    reason_huan:'',
    //选择售后类型
    after_sale_type:'',
    choose: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ 
      order_sn: options.order_sn,
      sku_id: options.sku_id || '',
      'returnForm.order_sn':options.order_sn,
      isCancel: !(options.sku_id),
      type:options.sku_id ? 'money' : 'money'
    })
    watch.setWatcher(this);//启用数据监听
    this.getAfterSaleData()
  },
  watch:{
    'returnForm.return_num':function(newVal){
      const { refund_price } = this.data.skuList[0]
      this.setData({
        'returnForm.return_money':Foundation.formatPrice(refund_price*newVal)
      })
    }
  },
  //货物状态
  actionSheet1(){
    this.setData({showActionsheet1:true})
  },
  btnClick1(e){
    console.log(e.detail.value);
    let index = e.detail.index;
    this.data.groups1.forEach((item,i)=>{
      if(index==i){
        this.setData({state:item.text,showActionsheet1:false})
      }
    })  
  },
  //退款/货理由
  actionSheet2(){
    this.setData({showActionsheet2:true})
  },
  btnClick2(e){
    console.log(e.detail.value);
    let index = e.detail.index;
    this.data.groups2.forEach((item,i)=>{
      if(index==i){
        this.setData({reason:item.text,showActionsheet2:false,'returnForm.refund_reason':item.text})
      }
    })  
  },
  //换货理由
  actionSheet3(){
    this.setData({showActionsheet3:true})
  },
  btnClick3(e){
    console.log(e.detail.value);
    let index = e.detail.index;
    this.data.groups3.forEach((item,i)=>{
      if(index==i){
        this.setData({reason_huan:item.text,showActionsheet3:false,'returnForm.refund_reason':item.text})
      }
    })  
  },
  //选择
  chooseType(e){
    let type = e.currentTarget.dataset.type;
    this.setData({
      after_sale_type:type,
      choose: false,
    })

  },
  //获取售后数据
  getAfterSaleData(){
    API_AfterSale.getAfterSaleData(this.data.order_sn,this.data.sku_id).then(response=>{
      this.setData({ order: response.order,skuList: response.sku_list })
      const { refund_price , num} = response.sku_list[0]
      this.data.returnForm.return_money = Foundation.formatPrice(refund_price*num)
      this.data.returnForm.order_price = Foundation.formatPrice(response.order.order_price)
      if(response.original_way === 'yes'){
        this.setData({ original_way: true,'returnForm.account_type':''})
      }
      if(response.sku_list && response.sku_list.length){
        response.sku_list.forEach(item => {
          if (!item.skuName) item.skuName = this.formatterSkuSpec(item)
          item.purchase_price = Foundation.formatPrice(item.purchase_price)
        })
        this.setData({
          'returnForm.return_num':response.sku_list[0].num,
          maxReturnNum:response.sku_list[0].num
        })
      }
      this.setData({
        order:response.order,
        skuList:response.sku_list,
        'returnForm.return_money':this.data.returnForm.return_money,
        'returnForm.order_price': this.data.returnForm.order_price
      })
    })
  },
  refundType(){this.setData({type:'money'})},
  returnType(){this.setData({type:'goods'})},
  showReasonselect() { this.setData({ reason_select: !this.data.reason_select })},
  showAccountselect() { this.setData({ account_select: !this.data.account_select })},
  reasonSelect(e) { this.setData({'returnForm.refund_reason':e.currentTarget.dataset.picker })},
  accountSelect(e) { this.setData({ 'returnForm.account_type': e.currentTarget.dataset.picker })},
  bankCustomerRemark(e) { this.setData({ 'returnForm.customer_remark': e.detail.value })},
  returnAccount(e) { this.setData({'returnForm.return_account':e.detail.value})},
  bankName(e) { this.setData({'returnForm.bank_name':e.detail.value})},
  bankDepositAame(e) { this.setData({'returnForm.bank_deposit_name':e.detail.value})},
  bankaccountName(e) { this.setData({'returnForm.bank_account_name':e.detail.value})},
  bankAccountNumber(e) { this.setData({'returnForm.bank_account_number':e.detail.value})},
  /** 更新申请退货数量 */
  handleUpdateReturnNum(e){
    const syboml = e.currentTarget.dataset.syboml
    if(syboml === '-'){
      if (this.data.returnForm.return_num >= 2) {
        this.setData({ 'returnForm.return_num': this.data.returnForm.return_num -= 1})
      }
    }else{
      if (this.data.returnForm.return_num < this.data.maxReturnNum) {
        this.setData({ 'returnForm.return_num': this.data.returnForm.return_num += 1 })
      }
    }
  },
  /** 规格格式化显示 */
  formatterSkuSpec(sku) {
    if (!sku.spec_list || !sku.spec_list.length) return ''
    return sku.spec_list.map(spec => spec.spec_value).join(' - ')
  },
  /** 提交申请 */
  handleSubmit(){
    console.log(this.data.returnForm,11111111)
    const params = JSON.parse(JSON.stringify(this.data.returnForm))
    const { after_sale_type } = this.data
    if (!this.handleCheckParams()) return false
    console.log(after_sale_type,14521)
    if (after_sale_type === 'tuikuan') {
      if (this.data.isCancel) {
        API_AfterSale.applyAfterSaleCancel(params).then(()=>{
          wx.showToast({ title: '申请成功' });
          setTimeout(() => {
            wx.navigateBack({ delta: 1 });
          }, 1000);
        })
      } else {
        params.sku_id = this.data.sku_id
        API_AfterSale.applyAfterSaleMoney(params).then(()=>{
          wx.showToast({ title: '申请成功' });
          setTimeout(() => {
            wx.navigateBack({ delta: 1 });
          }, 1000);
        })
      }
      console.log('退款')
    } else if(after_sale_type==='huanhuo'){
      API_AfterSale.applyAfterSaleExchange(params).then(()=>{
        wx.showToast({ title: '申请成功' });
          setTimeout(() => {
            wx.navigateBack({ delta: 1 });
          }, 1000);
      })
      console.log('换货')
    }else {
      // 申请退货
      console.log('申请退货')
      params.sku_id = this.data.sku_id
      API_AfterSale.applyAfterSaleGoods(params).then(()=>{
        wx.showToast({ title: '申请成功' });
        setTimeout(() => {
          wx.navigateBack({ delta: 1 });
        }, 1000);
      })
    }
  },
  /** 检查参数 */
  handleCheckParams(){
    const {type,returnForm:params,original_way} = this.data
    if(!params.refund_reason){
      wx.showToast({title: '请选择申请原因',icon:'none'})
      return false
    }
    // if(type === 'goods' && !params.return_num){
    //   wx.showToast({ title: '请输入申请数量', icon: 'none' })
    //   return false
    // }
    // if (!params.account_type && !original_way) {
    //   wx.showToast({ title: '请选择退款方式', icon: 'none' })
    //   return false
    // }
    // if (params.account_type !=='BANKTRANSFER' && !original_way && !params.return_account){
    //   wx.showToast({ title: '请输入退款账户', icon: 'none' })
    //   return false
    // }
    // 银行账户信息
    // if (params.account_type === 'BANKTRANSFER') {
    //   if (params.bank_name && params.bank_deposit_name && params.bank_account_name && params.bank_account_number) {
    //     return true
    //   } else {
    //     wx.showToast({ title: '请检查银行账户信息是否完整！', icon: 'none' })
    //     return false
    //   }
    // }
    return true
  }
})